import pandas as pd
import dataCleaning as dataCleaning
from flask import Flask
import json
import matplotlib.pyplot as plt

app = Flask(__name__)


# 地区 广州 深圳 杭州 上海 北京 成都 厦门。 招聘总数
# 获取招聘java岗位数量分析 按地区。中心地图
@app.route('/api/positionsByRegion', methods=['GET'])
def getPositionsByRegion():
    # 使用找到的支持中文的字体
    city_counts = boss_fp['city_name'].value_counts()
    # 将 Series 转换为字典
    result_dict = city_counts.to_dict()
    # 将字典转换为 JSON 字符串
    json_result = json.dumps(result_dict, ensure_ascii=False)
    # 打印 JSON 字符串
    return json_result


#   每个行业找人数量
@app.route('/api/positionsByIndustry', methods=['GET'])
def getPositionsByIndustry():
    df_expanded = boss_fp.explode('brand_industry')
    count_result = df_expanded.groupby('brand_industry').count()['id']
    # 对结果进行降序排序
    sorted_result = count_result.sort_values(ascending=False)
    # 将排序后的结果转换为 JSON 格式并避免 Unicode 转义
    json_result = json.dumps(sorted_result.to_dict(), ensure_ascii=False)
    return json_result


# 获取招聘岗位的数量
@app.route('/api/positionsCount', methods=['GET'])
def getPositionsCount():
    # boss_fp['jobCategory'] = boss_fp['jobCategory'].str.split('[, /]')  # 支持逗号、斜杠和空格作为分隔符
    df_expanded = boss_fp.explode('jobCategory')
    category_counts = df_expanded.groupby('jobCategory').size().reset_index(name='job_count')
    category_dict = dict(zip(category_counts['jobCategory'], category_counts['job_count']))
    return category_dict


# 获取每个职业的最高和最低工资的中位数
@app.route('/api/positionsMinAndMaxAvg', methods=['GET'])
def getPositionsMinAndMaxAvg():
    # 返回一个简单的 JSON 数据
    df_expanded = boss_fp.explode('jobCategory')
    # 进行分组，并计算每个组的最低工资和最高工资的中位数
    min_result = df_expanded.groupby('jobCategory')['min_salary'].median()
    max_result = df_expanded.groupby('jobCategory')['max_salary'].median()
    # 将结果转换为字典格式
    result_min_dict = min_result.to_dict()  # 最大值的中位数
    result_max_dict = max_result.to_dict()  # 最小值的中位数
    return {'max': result_max_dict, 'min': result_min_dict}


#  饼图 公司规模
@app.route('/api/getBrandIndustry', methods=['GET'])
def getBrandIndustry():
    count_result = boss_fp.groupby('brand_scale_name').size().reset_index(name='job_count')
    result = [{'value': row['job_count'], 'name': row['brand_scale_name']} for _, row in count_result.iterrows()]
    # 输出 JSON 格式的结果
    json_result = json.dumps(result, ensure_ascii=False, indent=2)
    # 打印结果
    return json_result


#  饼图 工龄分布
@app.route('/api/getJobExperience', methods=['GET'])
def getJobExperience():
    count_result = boss_fp.groupby('job_experience').size().reset_index(name='job_count')
    result = [{'value': row['job_count'], 'name': row['job_experience']} for _, row in count_result.iterrows()]
    # 输出 JSON 格式的结果
    json_result = json.dumps(result, ensure_ascii=False, indent=2)
    # 打印结果
    return json_result


#  饼图 学历要求
@app.route('/api/getJobDegree', methods=['GET'])
def getJobDegree():
    count_result = boss_fp.groupby('job_degree').size().reset_index(name='job_count')
    result = [{'value': row['job_count'], 'name': row['job_degree']} for _, row in count_result.iterrows()]
    # 输出 JSON 格式的结果
    json_result = json.dumps(result, ensure_ascii=False, indent=2)
    # 打印结果
    return json_result


# 获取线图
@app.route('/api/getLineChart', methods=['GET'])
def getLineChart():
    df_exploded = boss_fp.explode('jobCategory')
    # 筛选 jobCategory 只包含 'Java', 'Python', 'C' 的数据
    df_filtered = df_exploded[df_exploded['jobCategory'].isin(['Python', 'Java', 'CAndC++'])]
    # 按 jobCategory 和 job_degree 分组，统计每个 job_degree 的个数
    result = df_filtered.groupby(['jobCategory', 'job_degree']).size().reset_index(name='count')
    # 自定义学历顺序
    degree_order = ['学历不限', '中专/中技', '大专', '本科', '硕士', '博士']
    # 将 job_degree 按照自定义顺序排序
    result['job_degree'] = pd.Categorical(result['job_degree'], categories=degree_order, ordered=True)
    result = result.sort_values(by=['jobCategory', 'job_degree'])
    # 结果转成字典形式
    result_dict = {}
    # 填充字典，按 jobCategory 存储每个学历的计数
    for category in result['jobCategory'].unique():
        # 获取当前 jobCategory 下所有的学历计数
        degree_counts = result[result['jobCategory'] == category]['count'].tolist()
        # 补全学历列表，确保按学历顺序输出
        full_degrees = dict(zip(degree_order, [0] * len(degree_order)))
        for i, degree in enumerate(result[result['jobCategory'] == category]['job_degree']):
            full_degrees[degree] = degree_counts[i]
        result_dict[category] = list(full_degrees.values())
    return result_dict


if __name__ == "__main__":
    # 启动 Flask 服务并让其在后台运行
    boss_fp = pd.read_csv('../data/boss_data.csv')
    boss_fp['salary'] = boss_fp['salary_desc'].apply(dataCleaning.normalize_salary)
    boss_fp['jobCategory'] = boss_fp['job_name'].apply(
        lambda x: dataCleaning.classify_job(x, dataCleaning.job_keywords))
    boss_fp['min_salary'] = boss_fp['salary'].apply(dataCleaning.extract_min_salary)
    boss_fp['max_salary'] = boss_fp['salary'].apply(dataCleaning.extract_max_salary)
    boss_fp['jobCategory'] = boss_fp['jobCategory'].str.split('[, /]')
    boss_fp['brand_industry'] = boss_fp['brand_industry'].str.split('[, /]')  # 支持逗号、斜杠和空格作为分隔符
    boss_fp = boss_fp[boss_fp['jobCategory'] != 'Other']
    app.run(host='0.0.0.0', port=5001, debug=True, use_reloader=False)
